package com.powernode.teatraceability.typehandler;

import com.powernode.teatraceability.utils.Base64StrAndBytes;
import org.apache.ibatis.type.*;

import java.io.ByteArrayInputStream;
import java.sql.*;

/**
 * ClassName: Base64TypeHanlder
 * Description:
 *
 * @Author: jdz
 * @Create: 2023/5/14 - 16:02
 */
@MappedTypes(Base64StrAndBytes.class)
public class Base64TypeHanlder extends BaseTypeHandler<Base64StrAndBytes> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Base64StrAndBytes base64StrAndBytes, JdbcType jdbcType) throws SQLException {
        final byte[] parameter = base64StrAndBytes.getBase64Bytes();
        final ByteArrayInputStream bis = new ByteArrayInputStream(parameter);
        ps.setBinaryStream(i, bis, parameter.length);
    }

    @Override
    public Base64StrAndBytes getNullableResult(ResultSet rs, String s) throws SQLException {
        final Blob blob = rs.getBlob(s);
        byte[] returnValue = null;
        if (null != blob) {
            returnValue = blob.getBytes(1L, (int)blob.length());
        }
        return new Base64StrAndBytes(returnValue);
    }

    @Override
    public Base64StrAndBytes getNullableResult(ResultSet rs, int i) throws SQLException {
        Blob blob = rs.getBlob(i);
        byte[] returnValue = null;
        if (null != blob) {
            returnValue = blob.getBytes(1L, (int)blob.length());
        }
        return new Base64StrAndBytes(returnValue);
    }

    @Override
    public Base64StrAndBytes getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return null;
    }
}
